

class CarObject extends egret.DisplayObjectContainer {
    public body: Box2D.Dynamics.b2Body = null
    public leftEngine: number = 0
    public rightEngine: number = 0
    private _scene: GameScene = null
    public constructor(scene: GameScene) {
        super()
        this._scene = scene
        this._leftWheel = new WheelObject(this, -50, 0)
        this._rightWheel = new WheelObject(this, 50, 0)
    }

    private _sinBodyAngle: number = 0
    private _cosBodyAngle: number = 0
    public get SinBodyAngle(): number {
        return this._sinBodyAngle
    }
    public get CosBodyAngle(): number {
        return this._cosBodyAngle
    }
    private _leftWheel: WheelObject = null
    private _rightWheel: WheelObject = null

    public loadResource(): void {
        let bmp = new egret.Bitmap()
        bmp.texture = RES.getRes("player_png")
        bmp.anchorOffsetX = bmp.width / 2
        bmp.anchorOffsetY = bmp.height / 2
        this.addChild(bmp)
    }

    public initPhy(world: Box2D.Dynamics.b2World): void {
        let bodyDef = new Box2D.Dynamics.b2BodyDef()
        bodyDef.position = new Box2D.Common.Math.b2Vec2(0, 0);
        bodyDef.type = Box2D.Dynamics.b2Body.b2_dynamicBody;
        bodyDef.angularDamping = 0
        bodyDef.linearDamping = 0
        this.body = world.CreateBody(bodyDef)

        let w = GameScene.GetPhyLen(150)
        let h = GameScene.GetPhyLen(150)
        let poly = Box2D.Collision.Shapes.b2PolygonShape.AsOrientedBox(w / 2, h / 2, new Box2D.Common.Math.b2Vec2(0, 0));
        let fixtureDef = new Box2D.Dynamics.b2FixtureDef()
        fixtureDef.density = 1;
        fixtureDef.restitution = 0;
        fixtureDef.shape = poly;
        this.body.CreateFixture(fixtureDef)
    }

    public updateByPhy() {
        let angle = this.body.GetAngle() - Math.PI / 2
        let pos = this.body.GetPosition()
        this._sinBodyAngle = Math.sin(angle)
        this._cosBodyAngle = Math.cos(angle)

        this.rightEngine = this._scene.RightStickPercent * 50
        this.leftEngine = this._scene.LeftStickPercent * 50
        
        //if (this.leftEngine != 0 || this.rightEngine != 0) {
        console.log("Player角度: %d", angle / Math.PI * 180)
        this._rightWheel.AddForce(this.rightEngine)
        this._leftWheel.AddForce(this.leftEngine)
        //}

        if (this.x != pos.x || this.y != pos.y) {
            this.x = GameScene.GetEgretLen(pos.x)
            this.y = GameScene.GetEgretLen(pos.y)
            this.rotation = (angle + Math.PI / 2) / Math.PI * 180
            App.ControllerManager.applyFunc(ControllerConsts.GameMap, GameMapConsts.LookAtPlayer)
        }
    }
}